package com.yirui.bridge.config;

import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MissingRequestHeaderException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Dujie
 * @create 2025/7/24
 * @since 1.0.0
 */

public class GlobalHandlerExceptionResolver implements HandlerExceptionResolver, Ordered {

    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response,
                                         Object handler,
                                         Exception ex) {
        /*DefaultHandlerExceptionResolver a;
        if (ex instanceof MissingServletRequestParameterException) {
            MissingServletRequestParameterException msrpe = (MissingServletRequestParameterException) ex;
            try {
                response.setContentType("application/json");
                response.setStatus(HttpStatus.BAD_REQUEST.value());
                response.getWriter().write(String.format(
                        "{\"error\": \"Missing parameter\", \"param\": \"%s\", \"type\": \"%s\"}",
                        msrpe.getParameterName(),
                        msrpe.getParameterType()
                ));
                return new ModelAndView();
            } catch (IOException e) {
                // 处理IO异常
            }
        }else (ex instanceof MissingRequestHeaderException){

        }*/
        try {
            response.setContentType("application/json");
            response.setStatus(HttpStatus.BAD_REQUEST.value());
            response.getWriter().write(String.format(
                    "{\"error\": \"Missing parameter\", \"message\": \"%s\", \"success\": false}",
                    ex.toString()
            ));
            return new ModelAndView();
        } catch (IOException e) {
            // 处理IO异常
        }
        return null; // 让其他解析器处理
    }

    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE; // 高优先级
    }
}